import dynamic from 'next/dynamic'
import styles from './id.module.scss'
import { useEffect, useState, useMemo } from 'react'
import { isSexPureNumber, isPureNumber } from '@/utils/utils'
import { getImportSource } from '@/api/selfbuild'
import { useRouter } from 'next/router'
import Link from 'next/link'
import cm from 'classnames'
import Responsive from '@c/responsive'

const LiveIcon = dynamic(() => import('@c/live-icon'))
const PlayError = dynamic(() => import('@c/play-error'))
const VideoSportsHls = dynamic(() => import('@c/video/video-sports-hls'))
const VideoSportsMp4 = dynamic(() => import('@c/video/video-sports-mp4'))

//判断播放链接是rtmp或者flv展则不支持播放，引导播放
const isRtOrFlvOrCtv = url => {
  const simpleUrl = url.split('?')[0]
  if (simpleUrl.startsWith('rtmp:') || simpleUrl.endsWith('.flv') || simpleUrl.endsWith('.ctv')) {
    return true
  }
  return false
}

const Index = props => {
  const router = useRouter()
  const { asPath } = router
  const { id, episode } = props
  const [playError, setError] = useState(false) //播放错误
  const [currGroup, setCurrGroup] = useState({})
  const [name, setName] = useState('')
  const [playUrl, setPlayUrl] = useState('')
  const handlePlayError = () => {
    setError(true)
  }

  useEffect(() => {
    if (!currGroup?.source) {
      return
    }
    try {
      setPlayUrl(currGroup.source[+episode - 1].url)
      setName(currGroup.source[+episode - 1].name)
      setError(false)
    } catch (error) {
      router.replace('/404')
    }
  }, [currGroup, asPath])

  //初始加载数据自建
  const initData = async () => {
    const res = await getImportSource(localStorage.getItem('token'))
    const channels = (res.data?.sources || []).filter(item => item.id == id).pop() || {}
    if (!channels?.source) {
      router.replace('/404')
      return
    }
    channels.source = channels.source.filter(item => item.alive)
    setCurrGroup(channels)
  }
  useEffect(() => {
    // 平台
    initData()
    return () => {
      sessionStorage.setItem('lastPage', true)
    }
  }, [])

  const playNode = useMemo(() => {
    let isHls = true
    if (!playUrl) {
      return null
    }
    if (isRtOrFlvOrCtv(playUrl)) {
      setError(true)
      return null
    }
    const simpleUrl = playUrl.split('?')[0]
    if (simpleUrl.endsWith('.mp4')) {
      isHls = false
    }
    const finalPlayUrl = playUrl.replace('http://', 'https://')
    if (isHls) {
      return <VideoSportsHls from="CUSTOM" lineArr={[finalPlayUrl]} onError={handlePlayError} />
    }
    return <VideoSportsMp4 from="CUSTOM" lineArr={[finalPlayUrl]} src={finalPlayUrl} onError={handlePlayError} />
  }, [playUrl, asPath])

  return (
    <div className={styles.zj}>
      <Responsive className={styles.playContainer}>
        <div className={styles.playBox}>
          <div className={styles.play}>
            {playError ? <PlayError name={name} /> : null}
            {playNode}
          </div>
          <div className={cm(styles.sectionBox, 'hideWhenPhone')}>
            <h1 className={cm(styles.titleName, 'textEllipsis')}>{name}</h1>
            <div className={styles.jujiBox}>
              {currGroup?.source?.map((item, index) => {
                return (
                  <Link
                    href={`/zj/${id}/${index + 1}`}
                    replace
                    className={cm(styles.jujiItem, index + 1 == episode ? styles.jujiItemActive : '')}
                    key={index}
                  >
                    <span>{item.name}</span>
                    <LiveIcon className={styles.itemLiveIcon} />
                  </Link>
                )
              })}
            </div>
          </div>
        </div>
      </Responsive>
      <div className={cm(styles.sectionBoxPhone, 'hideWhenPc')}>
        <h1 className={cm(styles.titleName, 'textEllipsis')}>{name}</h1>
        <div className={cm(styles.jujiBox, 'scrollBeautify')}>
          {currGroup?.source?.map((item, index) => {
            return (
              <Link
                href={`/zj/${id}/${index + 1}`}
                replace
                className={cm(styles.jujiItem, index + 1 == episode ? styles.jujiItemActive : '')}
                key={index}
              >
                <span className="textEllipsis">{item.name}</span>
                <LiveIcon className={styles.itemLiveIcon} />
              </Link>
            )
          })}
        </div>
      </div>
    </div>
  )
}

export default Index

export async function getServerSideProps({ params }) {
  const { id, episode } = params
  // 去到404页面
  if (!isSexPureNumber(id) || !isPureNumber(episode)) {
    return { notFound: true }
  }
  const layoutProps = {
    noSomeMetaInfo: false,
    url: '/zj',
    title: '自建频道分享观看 - 星视界',
    desc: '打开星视界，分享更多自建源！'
  }
  return {
    props: {
      layoutProps,
      id,
      episode
    }
  }
}
